package server;

import org.dom4j.*;
import org.dom4j.io.SAXReader;
import server.mapper.Mapper;
import server.mapper.MyContext;
import server.mapper.MyHost;
import server.mapper.MyWrapper;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.*;
import java.util.concurrent.*;

/**
 * Minicat的主类
 */
public class Bootstrap {

    /**定义socket监听的端口号*/
    private int port = 8080;

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }


    /**
     * Minicat启动需要初始化展开的一些操作
     */
    public void start() throws Exception {
        System.out.println("start方法开始执行：====");

        Mapper mapper = new Mapper();
        List<MyHost> myHosts = new ArrayList<>();

        //首先解析加载server.xml
        loadServer(myHosts);
        mapper.setHosts(myHosts);//封装第一层host

        for (MyHost myHost: myHosts ) {
            System.out.println("开始循环myHosts：====");
            List<MyContext> myContexts = new ArrayList<>();

            //然后扫描webapp下的所有文件，获取所有context，即项目名称
            ArrayList<String> listFileName = new ArrayList<String>();
//            List<String> projectNames = getAllProjectName("D:\\webapps\\");
            List<String> projectNames = getAllProjectName(myHost.getAppBase()+"\\");
//            getAllFileName("D:\\webapps\\",listFileName);

            FileInputStream resourceAsStream;
            String webxmlUrl="";
//            List<Myclass> myclasses=new ArrayList<>();

            for(String projectUrl:projectNames){
                System.out.println("开始循环projectNames：====");
//                System.out.println(projectUrl);
                String[] strings = projectUrl.split("\\\\");
                //封装第二层context
                MyContext myContext = new MyContext(projectUrl,strings[strings.length-1]);

                myContexts.add(myContext);
            }
            myHost.setContexts(myContexts);


            for (MyContext myContext:myContexts) {
                System.out.println("开始循环myContexts：====");
//              System.out.println(myContext.getProjectUrl());
                getAllFileName(myContext.getProjectUrl()+"\\",listFileName);

                String classURL="";

                for(String name:listFileName){
                    boolean b = true;
                    if(name.contains("web.xml")){
                        webxmlUrl=name;
                    }
                    if(name.contains("classes")&&b){

                        String[]  strings = name.split("\\\\");
                        int i = strings.length;

                        if (strings[i-1].equals("classes"))
                        {
                            classURL=name;
                            b=false;
                        }

                    }
                }
//                System.out.println("classURL"+classURL);

                //解析每个项目的web.xml
                resourceAsStream = new FileInputStream(webxmlUrl);
                List<MyWrapper> myWrappers = loadServlet(resourceAsStream,classURL);
                //封装wrapper
                myContext.setWrappers(myWrappers);
                //mapper至此封装完毕
            }



        }


        // 定义一个线程池
        int corePoolSize = 10;
        int maximumPoolSize =50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();


        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );





        /*
            完成Minicat 1.0版本
            需求：浏览器请求http://localhost:8080,返回一个固定的字符串到页面"Hello Minicat!"
         */
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("=====>>>Minicat start on port：" + port);
        /*while(true) {
            Socket socket = serverSocket.accept();
            // 有了socket，接收到请求，获取输出流
            OutputStream outputStream = socket.getOutputStream();
            String data = "Hello Minicat!";
            String responseText = HttpProtocolUtil.getHttpHeader200(data.getBytes().length) + data;
            outputStream.write(responseText.getBytes());
            socket.close();
        }*/
        /**
         * 完成Minicat 2.0版本
         * 需求：封装Request和Response对象，返回html静态资源文件
         */
        /*while(true) {
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            response.outputHtml(request.getUrl());
            socket.close();

        }*/
        /**
         * 完成Minicat 3.0版本
         * 需求：可以请求动态资源（Servlet）
         */
        /*while(true) {
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            // 静态资源处理
            if(servletMap.get(request.getUrl()) == null) {
                response.outputHtml(request.getUrl());
            }else{
                // 动态资源servlet请求
                HttpServlet httpServlet = servletMap.get(request.getUrl());
                httpServlet.service(request,response);
            }

            socket.close();

        }
*/
        /*
            多线程改造（不使用线程池）
         */
        /*while(true) {
            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket,servletMap);
            requestProcessor.start();
        }*/

        System.out.println("=========>>>>>>使用线程池进行多线程改造");
        /*
            多线程改造（使用线程池）
         */
        while(true) {
            System.out.println("监听到sorket请求----->");
            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket,mapper);
            //requestProcessor.start();
            threadPoolExecutor.execute(requestProcessor);
        }



    }


//    private Map<String,HttpServlet> servletMap = new HashMap<String,HttpServlet>();


    /**
     * 加载解析server.xml
     */
    private void loadServer(List<MyHost> myHosts) {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("server.xml");
        SAXReader saxReader = new SAXReader();

        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            List<Element> selectNodes = rootElement.selectNodes("//Server");
            for (int i = 0; i < selectNodes.size(); i++) {

                Element element =  selectNodes.get(i);
                // <Service>
                //        <Connector port="8080"/>
                //        <Engine>
                //            <Host name="localhost" appBase="D:\webapps">
                //            </Host>
                //        </Engine>
                //    </Service>
                Element serviceElement = (Element) element.selectSingleNode("Service");

                Element engineElement = (Element) serviceElement.selectSingleNode("Engine");

                Element hostElement = (Element) engineElement.selectSingleNode("Host");
                Attribute hostattribute0 = hostElement.attribute(0);
                Attribute hostattribute1 = hostElement.attribute(1);

//                System.out.println("hostattribute0Name:"+hostattribute0.getName());//:name
//                System.out.println("hostattribute0Value:"+hostattribute0.getValue());//:localhost
//                System.out.println("hostattribute1Name:"+hostattribute1.getName());//:appBase
//                System.out.println("hostattribute1Value:"+hostattribute1.getValue());//D:\webapps

                MyHost myHost = new MyHost(hostattribute0.getValue(),hostattribute1.getValue());

                myHosts.add(myHost);

            }

        } catch (DocumentException e) {
            e.printStackTrace();
        }



    }




    /**
     * 加载解析web.xml，初始化Servlet
     */
    private List<MyWrapper> loadServlet(FileInputStream resourceAsStream, String classUrl) {

        List<MyWrapper> myWrappers = new ArrayList<>();
        SAXReader saxReader = new SAXReader();

        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            List<Element> selectNodes = rootElement.selectNodes("//servlet");
            for (int i = 0; i < selectNodes.size(); i++) {

                Element element =  selectNodes.get(i);
                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletnameElement.getStringValue();
//                System.out.println("servletName: "+servletName);

                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletclassElement.getStringValue();
//                System.out.println("servletClass: "+servletClass);

                //获取servlet类文件名
                String[] strings = servletClass.split("\\.");
                int l = strings.length;
                String servletclassName = strings[l-1]+".class";
//                System.out.println("servletclassName: "+servletclassName);


                // 根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                // /lagou
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
//                System.out.println("urlPattern: "+urlPattern);

                //获取servlet类实例方法
                PathClassLoader pathClassLoader = new PathClassLoader(classUrl);//"D:/webapps/web_demo_war_exploded/WEB-INF/classes"

                Class clazz = pathClassLoader.findClass(servletClass.replace(".","/"));//全限定类名 servletClass   for example：com/lagou/edu/servlet/TestServlet
                //利用Java反射机制创建实例测试方法
                HttpServlet httpServlet = (HttpServlet)clazz.newInstance();

                httpServlet.doGet(null,null);

                //封装wrapper
                MyWrapper myWrapper = new MyWrapper(urlPattern,httpServlet);
                myWrappers.add(myWrapper);

            }



        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }


        return myWrappers;
    }



    /**
     *  获取一个文件夹下的所有文件全路径
     * @param path
     * @param listFileName
     */
    public static void getAllFileName(String path, ArrayList<String> listFileName){
        File file = new File(path);
        File [] files = file.listFiles();
        String [] names = file.list();

        if(names != null){
            String [] completNames = new String[names.length];
            for(int i=0;i<names.length;i++){
                completNames[i]=path+names[i];
            }
            listFileName.addAll(Arrays.asList(completNames));
        }

        for(File a:files){
            if(a.isDirectory()){//如果文件夹下有子文件夹，获取子文件夹下的所有文件全路径。
                getAllFileName(a.getAbsolutePath()+"\\",listFileName);
            }
        }

    }

    public static List<String> getAllProjectName(String path){
        List<String> projectNames= new ArrayList<>();
        File file = new File(path);
        File [] files = file.listFiles();
        String [] names = file.list();
        if(names != null){
            String [] completNames = new String[names.length];
            for(int i=0;i<names.length;i++){
                completNames[i]=path+names[i];
            }
            projectNames.addAll(Arrays.asList(completNames));
        }

        return projectNames;
    }




    /**
     * Minicat 的程序启动入口
     * @param args
     */
    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap();
        try {
            // 启动Minicat
            bootstrap.start();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
